package cn.wolfcode.web.controller;


import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CommonCodeMsg;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


@RestController
@RequestMapping("/orderPay")
@RefreshScope
public class OrderPayController {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Value("${pay.frontEndPayUrl}")
    private String frontEndPayUrl;

    
    @RequireLogin
    @GetMapping("/alipay")
    public Result alipay(String orderNo, Integer type){
        if (StringUtils.isEmpty(orderNo)||StringUtils.isEmpty(type)){
            throw new BusinessException(CommonCodeMsg.NO_PARAM_ERROR);
        }
        
        if (type == OrderInfo.PAYTYPE_ONLINE){
            //在线支付
            return Result.success(orderInfoService.payOnLine(orderNo));
            
        }else{
          return Result.success(orderInfoService.payByIntergral(orderNo));
        }

    }
    @RequestMapping("/notify_url")
    public String notify_url(@RequestParam Map<String, String> params){
    if (StringUtils.isEmpty(params)){
        throw new BusinessException(CommonCodeMsg.NO_PARAM_ERROR);
    }
        String result=orderInfoService.notifyService(params);
        return result;
    }
    
    @RequestMapping("/return_url")
    public void return_url(@RequestParam Map<String, String> params,HttpServletResponse response){
        String ret="success";
        if (StringUtils.isEmpty(params)){
            throw new BusinessException(CommonCodeMsg.NO_PARAM_ERROR);
        }
      Boolean value=orderInfoService.returnService(params);
if (value){
    //成功
    try {
        response.sendRedirect(frontEndPayUrl+params.get("out_trade_no"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    
}else {
    throw  new BusinessException(SeckillCodeMsg.PAY_SERVER_ERROR);
}
    }
    
@RequestMapping("/refund")
    public Result refund(String orderNo){
        if (orderNo==null){
            throw new BusinessException(CommonCodeMsg.NO_PARAM_ERROR);
        }
    
        return Result.success(orderInfoService.refund(orderNo));
}
    
    
}
